package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.AppUserDTO;
import com.sky.dto.AppUserLoginDTO;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.AppUser;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.bcel.classfile.Constant;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.net.http.HttpClient;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    public static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    private final WeChatProperties wChatProperties;

    private final UserMapper userMapper;

    @Autowired
    public  UserServiceImpl(WeChatProperties wChatProperties, UserMapper userMapper) {
        this.wChatProperties= wChatProperties;
        this.userMapper = userMapper;
    }

    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        // 调用微信接口实现登录,获得当前微信用户的openid
        String openid = getOpenid(userLoginDTO);
        // 判断openid是否为空,如果为空表示登录失败,抛出业务异常
        if (openid==null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        // 判断当前微信用户是否为新用户,如果是新用户就自动完成注册
        User user = userMapper.getByOpenid(openid);
        if (user==null){
            user=User.builder()
                    .openid(openid)
                    .build();
            userMapper.insert(user);
        }
        // 返回用户对象
        return user;
    }

    @Override
    public boolean addAppUser(AppUserDTO appUserDTO) {
        //TODO 添加头像数据
        AppUser appUser=new AppUser();
        BeanUtils.copyProperties(appUserDTO, appUser);
        appUser.setCreateTime(LocalDateTime.now());
        //md5加密
        appUser.setPassword(DigestUtils.md5DigestAsHex(appUserDTO.getPassword().getBytes()));
        return userMapper.insertAppUser(appUser)>0;
    }

    @Override
    public AppUser appLogin(AppUserLoginDTO appUserLoginDTO) {
        AppUser user = userMapper.selectByAppUserName(appUserLoginDTO.getUsername());
        if (user==null)
        {
            throw new LoginFailedException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        String password = DigestUtils.md5DigestAsHex(appUserLoginDTO.getPassword().getBytes());
        if (!user.getPassword().equals(password))
        {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        return user;
    }

    @Override
    public AppUser getById(Long id) {
        return userMapper.getAppUserById(id);
    }

    @Override
    public void update(AppUser appUser) {
        if (appUser.getPassword()!=null)
            appUser.setPassword(DigestUtils.md5DigestAsHex(appUser.getPassword().getBytes()));
        userMapper.updateAppUser(appUser);
    }

    /**
     * 调用微信接口服务获取openid
     * @param userLoginDTO
     * @return
     */
    private String getOpenid(UserLoginDTO userLoginDTO) {
        //https://mp.weixin.qq.com/wxamp/devprofile/get_profile?token=1704677920&lang=zh_CN
        Map<String, String> map=new HashMap<>();
        map.put("appid",wChatProperties.getAppid());// 小程序的appid wx0772abfae15a197a
        map.put("secret",wChatProperties.getSecret());// 小程序的secret 1914f15f5240ed8fff7a81e454d33f0a
        map.put("js_code",userLoginDTO.getCode()); // 小程序调用wx.login返回的code
        map.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN_URL,map);
        JSONObject jsonObject=JSONObject.parseObject(json);
        return jsonObject.getString("openid");
    }
}
